<?php

namespace Mogod\Core\MethodBroker;

require_once __DIR__ . '/MethodBrokerAbstract.php';

/**
 *
 * Коллекция брокеров методов
 *
 * @author goorus, morph
 *
 */
class MethodBrokerComposite extends MethodBrokerAbstract
{

	/**
	 * Добавленные брокеры
	 *
	 * @var array of Mogod\Core\MethodBroker\MethodBrokerAbstract
	 */
	protected $brokers = array();

	/**
	 * Добавляет брокер в список
	 *
	 * @param Mogod\Core\MethodBroker\MethodBrokerAbstract $broker
	 * @return Mogod\Core\MethodBroker\MethodBrokerComposite
	 */
	public function add($broker)
	{
		$this->brokers[] = $broker;
		return $this;
	}

	/**
	 * Очищает список хэндлеров
	 *
	 * @return Mogod\Core\MethodBroker\MethodBrokerComposite
	 */
	public function clear()
	{
		$this->brokers = array();
		return $this;
	}

	/**
	 * Получить весь список брокеров
	 *
	 * @return array of Mogod\Core\MethodBroker\MethodBrokerAbstract
	 */
	public function getBrokers()
	{
		return $this->brokers;
	}

	/**
	 * @inheritdoc
	 */
	public function call($object, $method, array $args)
	{
		$result = null;
		foreach ($this->brokers as $broker) {
			$current = $broker->call($object, $method, $args);
			$result = $current ?: $result;
		}
		return $result;
	}

	/**
	 * Удаляет брокер из списка
	 *
	 * @param Mogod\Core\MethodBroker\MethodBrokerAstract $broker
	 * @return Mogod\Core\MethodBroker\MethodBrokerComposite
	 */
	public function remove($broker)
	{
		foreach ($this->brokers as $key => $value) {
			if ($broker === $value) {
				unset($this->brokers[$key]);
				break;
			}
		}
		return $this;
	}

}
